package mobi.yuanshen.service.impl;

import lombok.extern.slf4j.Slf4j;
import mobi.yuanshen.mapper.DeptMapper;
import mobi.yuanshen.mapper.EmpMapper;
import mobi.yuanshen.pojo.Dept;
import mobi.yuanshen.pojo.DeptLog;
import mobi.yuanshen.pojo.Emp;
import mobi.yuanshen.service.DeptLogService;
import mobi.yuanshen.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delById(Integer id) throws Exception {
        try {
            deptMapper.delById(id); // 删除部门
            List<Emp> emps = empMapper.queryEmpsByDepId(id);
            log.info("将删除以下的部门员工信息信息:");
            System.out.println("-------------------------------------------");
            emps.forEach((item) -> {
                System.out.println(item);
            });
            System.out.println("-------------------------------------------");
            empMapper.deleteEmpByDepId(id); // 删除部门下的员工
        } finally {
            // 记录操作日志
            DeptLog deptLog = new DeptLog(null,
                    LocalDateTime.now(),
                    "执行了解散部门的操作,被解散部门的id:" + id);
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    /**
     * 根据id查询部门
     * @return
     */
    @Override
    public Dept queryById(Integer id) {
        return deptMapper.queryById(id);
    }

    /**
     * 更新部门信息
     * @param dept
     * @return
     */
    @Override
    public Integer updateDept(Dept dept) {
        return deptMapper.updateDept(dept);
    }

}
